<template>
  <div class="share-create-container">
    <Header title="创建分享" show-back />

    <div class="share-create-content">
      <!-- 文件信息 -->
      <div v-if="fileInfo" class="file-card">
        <div class="file-icon">
          <van-icon
            :name="getFileIcon(fileInfo)"
            :color="getFileIconColor(fileInfo)"
            size="24"
          />
        </div>
        <div class="file-info">
          <div class="file-name">{{ fileInfo.fileName }}</div>
          <div class="file-meta">
            <span v-if="!fileInfo.isFolder && fileInfo.fileSize">{{ formatFileSize(fileInfo.fileSize) }}</span>
            <span>{{ formatTime(fileInfo.updateTime) }}</span>
          </div>
        </div>
      </div>

      <!-- 分享配置表单 -->
      <van-form @submit="handleCreateShare">
        <van-cell-group title="分享设置" inset>
          <van-field
            v-model="shareForm.shareName"
            name="shareName"
            label="分享名称"
            placeholder="请输入分享名称"
            :rules="[{ required: true, message: '请输入分享名称' }]"
          />

          <van-field label="访问权限">
            <template #input>
              <van-radio-group v-model="shareForm.permissions" direction="horizontal">
                <van-radio :name="1">仅预览</van-radio>
                <van-radio :name="2">可下载</van-radio>
              </van-radio-group>
            </template>
          </van-field>

          <van-field label="提取码">
            <template #input>
              <div class="password-setting">
                <van-switch v-model="shareForm.needPassword" />
                <van-field
                  v-if="shareForm.needPassword"
                  v-model="shareForm.password"
                  placeholder="4位提取码"
                  maxlength="4"
                  style="flex: 1; margin-left: 12px;"
                  :rules="passwordRules"
                >
                  <template #button>
                    <van-button size="small" @click="generatePassword">
                      随机生成
                    </van-button>
                  </template>
                </van-field>
              </div>
            </template>
          </van-field>

          <van-field label="有效期">
            <template #input>
              <van-radio-group v-model="shareForm.expireDays" direction="horizontal">
                <van-radio :name="1">1天</van-radio>
                <van-radio :name="7">7天</van-radio>
                <van-radio :name="30">30天</van-radio>
                <van-radio :name="-1">永久</van-radio>
              </van-radio-group>
            </template>
          </van-field>
        </van-cell-group>

        <div class="submit-section">
          <van-button
            round
            block
            type="primary"
            native-type="submit"
            :loading="loading"
          >
            创建分享
          </van-button>
        </div>
      </van-form>
    </div>

    <!-- 分享结果弹窗 -->
    <van-popup
      v-model:show="showResultPopup"
      position="bottom"
      :style="{ height: '50%' }"
      round
      closeable
    >
      <div class="share-result">
        <div class="result-header">
          <h3>分享创建成功</h3>
        </div>

        <div class="result-content">
          <van-cell-group inset>
            <van-cell
              title="分享链接"
              :value="shareResult.shareUrl"
              is-link
              @click="copyShareUrl"
            />
            <van-cell
              v-if="shareResult.password"
              title="提取码"
              :value="shareResult.password"
            />
          </van-cell-group>

          <div class="result-actions">
            <van-button
              block
              type="primary"
              @click="copyShareContent"
            >
              复制分享内容
            </van-button>
            <van-button
              block
              @click="goToShareList"
            >
              查看我的分享
            </van-button>
          </div>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { showToast, showLoadingToast, closeToast } from 'vant'
import Header from '@/components/Header.vue'
import { useFileStore } from '@/stores/file'
import { createShare, type CreateShareParams } from '@/api/share'
import type { FileInfo } from '@/api/file'

const router = useRouter()
const route = useRoute()
const fileStore = useFileStore()

// 状态
const loading = ref(false)
const showResultPopup = ref(false)
const fileInfo = ref<FileInfo | null>(null)

// 分享表单
const shareForm = ref({
  shareName: '',
  permissions: 2,
  needPassword: false,
  password: '',
  expireDays: 7
})

// 分享结果
const shareResult = ref({
  shareCode: '',
  shareUrl: '',
  password: ''
})

// 密码验证规则
const passwordRules = computed(() => [
  {
    validator: (value: string) => {
      if (shareForm.value.needPassword && (!value || value.length !== 4)) {
        return '请输入4位提取码'
      }
      return true
    }
  }
])

// 方法
const { formatFileSize, formatTime } = fileStore

const getFileIcon = (file: FileInfo) => {
  if (file.isFolder === 1) {
    return 'folder-o'
  }

  const ext = file.fileName.split('.').pop()?.toLowerCase()
  switch (ext) {
    case 'jpg':
    case 'jpeg':
    case 'png':
    case 'gif':
    case 'bmp':
    case 'webp':
      return 'photo-o'
    case 'mp4':
    case 'avi':
    case 'mov':
    case 'wmv':
    case 'flv':
      return 'video-o'
    case 'mp3':
    case 'wav':
    case 'aac':
    case 'flac':
      return 'music-o'
    case 'pdf':
      return 'description'
    case 'doc':
    case 'docx':
      return 'description'
    case 'xls':
    case 'xlsx':
      return 'description'
    case 'ppt':
    case 'pptx':
      return 'description'
    case 'txt':
      return 'notes-o'
    case 'zip':
    case 'rar':
    case '7z':
      return 'bag-o'
    default:
      return 'description'
  }
}

const getFileIconColor = (file: FileInfo) => {
  if (file.isFolder === 1) {
    return '#1989fa'
  }

  const ext = file.fileName.split('.').pop()?.toLowerCase()
  switch (ext) {
    case 'jpg':
    case 'jpeg':
    case 'png':
    case 'gif':
    case 'bmp':
    case 'webp':
      return '#ff976a'
    case 'mp4':
    case 'avi':
    case 'mov':
    case 'wmv':
    case 'flv':
      return '#ff976a'
    case 'mp3':
    case 'wav':
    case 'aac':
    case 'flac':
      return '#07c160'
    case 'pdf':
      return '#ee0a24'
    case 'doc':
    case 'docx':
      return '#1989fa'
    case 'xls':
    case 'xlsx':
      return '#07c160'
    case 'ppt':
    case 'pptx':
      return '#ff976a'
    default:
      return '#969799'
  }
}

const generatePassword = () => {
  const chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  let password = ''
  for (let i = 0; i < 4; i++) {
    password += chars.charAt(Math.floor(Math.random() * chars.length))
  }
  shareForm.value.password = password
}

const handleCreateShare = async () => {
  if (!fileInfo.value) {
    showToast('文件信息不存在')
    return
  }

  if (shareForm.value.needPassword && shareForm.value.password.length !== 4) {
    showToast('请输入4位提取码')
    return
  }

  loading.value = true
  showLoadingToast({
    message: '正在创建分享...',
    duration: 0
  })

  try {
    // 计算过期时间
    let expireTimeStr = ''
    if (shareForm.value.expireDays > 0) {
      const expireDate = new Date()
      expireDate.setDate(expireDate.getDate() + shareForm.value.expireDays)
      expireTimeStr = expireDate.toISOString().slice(0, 19).replace('T', ' ')
    }

    const params: CreateShareParams = {
      fileId: fileInfo.value.id,
      shareName: shareForm.value.shareName,
      permissions: shareForm.value.permissions,
      password: shareForm.value.needPassword ? shareForm.value.password : undefined,
      expireTimeStr: expireTimeStr || undefined
    }

    const share = await createShare(params)

    // 生成分享链接
    const baseUrl = window.location.origin
    const shareUrl = `${baseUrl}/share/${share.shareCode}`

    shareResult.value = {
      shareCode: share.shareCode,
      shareUrl,
      password: shareForm.value.needPassword ? shareForm.value.password : ''
    }

    closeToast()
    showResultPopup.value = true

    showToast({
      type: 'success',
      message: '分享创建成功'
    })
  } catch (error: any) {
    closeToast()
    showToast({
      type: 'fail',
      message: error.message || '创建分享失败'
    })
  } finally {
    loading.value = false
  }
}

const copyShareUrl = async () => {
  try {
    await navigator.clipboard.writeText(shareResult.value.shareUrl)
    showToast({
      type: 'success',
      message: '分享链接已复制'
    })
  } catch (error) {
    showToast({
      type: 'fail',
      message: '复制失败'
    })
  }
}

const copyShareContent = async () => {
  try {
    let copyText = `分享链接: ${shareResult.value.shareUrl}`
    if (shareResult.value.password) {
      copyText += `\n提取码: ${shareResult.value.password}`
    }
    await navigator.clipboard.writeText(copyText)
    showToast({
      type: 'success',
      message: '分享内容已复制'
    })
  } catch (error) {
    showToast({
      type: 'fail',
      message: '复制失败'
    })
  }
}

const goToShareList = () => {
  router.replace('/share')
}

// 获取文件信息
const loadFileInfo = async () => {
  const fileId = route.query.fileId as string
  if (!fileId) {
    showToast('缺少文件ID参数')
    router.back()
    return
  }

  try {
    // 从当前文件列表中查找文件信息
    const { fileList } = fileStore
    const file = fileList.find(f => f.id === parseInt(fileId))

    if (file) {
      fileInfo.value = file
      shareForm.value.shareName = file.fileName
    } else {
      showToast('文件不存在')
      router.back()
    }
  } catch (error) {
    showToast('获取文件信息失败')
    router.back()
  }
}

onMounted(() => {
  loadFileInfo()
})
</script>

<style scoped>
.share-create-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f8f8f8;
}

.share-create-content {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
}

.file-card {
  display: flex;
  align-items: center;
  padding: 16px;
  margin-bottom: 16px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.file-icon {
  margin-right: 12px;
  flex-shrink: 0;
}

.file-info {
  flex: 1;
  min-width: 0;
}

.file-name {
  font-size: 16px;
  color: #323233;
  margin-bottom: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.file-meta {
  font-size: 12px;
  color: #969799;
  display: flex;
  gap: 8px;
}

.password-setting {
  display: flex;
  align-items: center;
  width: 100%;
}

.submit-section {
  margin-top: 24px;
  padding: 0 16px;
}

.share-result {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.result-header {
  padding: 16px 20px;
  border-bottom: 1px solid #ebedf0;
  text-align: center;
}

.result-header h3 {
  margin: 0;
  font-size: 18px;
  color: #323233;
}

.result-content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

.result-actions {
  margin-top: 20px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

:deep(.van-cell-group--inset) {
  margin: 16px 0;
}

:deep(.van-radio-group) {
  display: flex;
  gap: 16px;
}

:deep(.van-field__control) {
  text-align: right;
}
</style>